import {Component, OnInit} from '@angular/core';
import {MsgResult} from "../../../../../models/msg-result";
import {MsgConstants} from "../../../../../constants/constants";
import {Content} from "../content";
import {FormGroup, FormBuilder, Validators} from "@angular/forms";
import {Router, ActivatedRoute} from "@angular/router";
import {PageSubject} from "../../../../../util/page-subject";
import {OneDialogService} from "../../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../../util/response-util";
import {Path} from "../../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {RecordService} from "./../record.service";
import {Type} from "./../Type";

declare var $;
declare var moment;

@Component({
  selector: 'app-record-deal',
  templateUrl: './record-deal.component.html',
  styleUrls: ['./record-deal.component.css']
})
export class RecordDealComponent implements OnInit {
  cont: Content;
  flag: boolean = false;
  contentForm: FormGroup;
  types: Array<Type> = [{code: '1', name: '标准站'}, {code: '2', name: '微型站'}, {code: '3', name: '工业废气'}, {
    code: '4',
    name: '扬尘'
  },
    {code: '5', name: '油烟'}, {code: '6', name: '喷漆房'}, {code: '7', name: '加油站'}, {code: '8', name: '工业废水'}, {
      code: '9',
      name: '水质断面'
    }
    , {code: '0', name: '因子报警'}];

  constructor(private router: Router,
              private route: ActivatedRoute,
              private pageSubject: PageSubject,
              private fb: FormBuilder,
              private dialogService: OneDialogService,
              private responseUtil: ResponseUtil,
              private recordService: RecordService) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    this.initRecordForm();
    // this.iniHandler();
  }


  /**
   * 构造表单
   */

  /**
   * 构造表单
   */
  private buildForm(): void {
    this.contentForm = this.fb.group({
      'id': [this.cont.id],
      'siteCode': [this.cont.siteCode],
      'siteName': [this.cont.sendTime],
      'sendTime': [this.cont.sendTime],
      'content': [this.cont.content],
      'type': [{value: this.cont.type, disabled: true}],
      'sendMode': [{value: this.cont.sendMode, disabled: true}],
      'handleStatus': [{value: this.cont.handleStatus, disabled: true}],
      'handler': [this.cont.handler]
      // 'handler': [this.cont.handler,[
      //   Validators.required,
      //   Validators.maxLength(14),
      //   Validators.pattern(/(^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$)|(^\d{3,4}-?\d{7,9}$)/)
      // ]]
    });

    this.contentForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }

  private onValueChanged(data ?: any) {
    if (!this.contentForm) {
      return;
    }
    const form = this.contentForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'handler': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'handler': {
      'required': '处理人不能为空',
      'maxlength': '长度不能超过14位',
      'pattern': '格式不正确'
    }

  };


  /**
   *
   */
  private initObject() {
    this.cont = new Content();
    this.buildForm();
  }

  /**
   * 面包屑
   */
  private pushPage() {
    let path = new Path("报警信息", "");
    this.pageSubject.pushPage("报警信息", "警情处理", path);
  }

  initRecordForm() {
    let id = this.route.snapshot.params["id"];
    if (!!id) {
      this.recordService.getMsgContentById(id).subscribe(
        result => this.responseUtil.success(result, this.processInitRecordResult),
        error => this.responseUtil.error(error)
      );
    }
  }

  private processInitRecordResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.cont = result.data;
      this.contentForm.patchValue(this.cont);
      console.log(this.cont.siteCode + this.cont.siteName);
      if (this.cont.handleStatus == '1') {
        $("#content_deal_handler").prop("disabled", true);//不可用
        this.flag = true;
      }

    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 实现处理
   */
  onSubmit() {
    this.cont = this.contentForm.value;
    console.log(this.cont.handleStatus);
    this.cont.handleTime = moment.now();
    this.recordService.dealRecord(this.cont).subscribe(
      result => this.responseUtil.success(result, this.processContentResult),
      message => this.responseUtil.error(message)
    );
  }

  private processContentResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
      //this.canceldeal();
      this.dialogService.successWithCancelBtn(result.message, () => this.canceldeal())

    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  yesClickFun(e) {
    if ($("#content_deal_handleStatus").val() == '1') {
      $("#content_deal_handler").prop("disabled", true);//不可用
    }

  }


  /**
   * 取消处理
   */
  canceldeal() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

}
